package com.oms.module.merchant.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.oms.common.HttpResult;
import com.oms.common.ResponseDTO;
import com.oms.module.merchant.constant.MerChantResponseCodeConstant;
import com.oms.module.merchant.domain.entity.UserEntity;
import com.oms.module.merchant.domain.vo.UserModifyPasswordVO;
import com.oms.module.merchant.domain.vo.UserRegVO;
import com.oms.module.merchant.service.UserService;
import com.oms.util.TextMessageVerificationTools;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.val;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.time.Instant;
import java.util.Date;
import java.util.Random;
import java.util.concurrent.TimeUnit;

import static java.util.Objects.isNull;

/**
 * @Author zhanghailong QQ38592077
 * @Description TODO
 * @Date 2020/7/3 10:24
 */
@RestController
@RequestMapping("/user")
@Api("商家端登陆注册 @author zhl ")
public class LoginRegistrationController {

    @Autowired
    TextMessageVerificationTools textMessageVerificationTools;
    @Resource
    RedisTemplate<String, Integer> redisTemplate;
    @Resource
    UserService userService;

    @PostMapping(value = "/getVerificationCode")
    @ApiOperation("获取验证码 @author zhl")
    public ResponseDTO getVerificationCode(HttpServletResponse response, HttpServletRequest request, String number, String sign) {
        //获取Ip
        String comma = ",";
        String localhostIP = "0:0:0:0:0:0:0:1";
        String commonIP = "0.0.0.0.0.0.0.1%0";
        String ip = request.getHeader("x-forwarded-for");
        if (isNull(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        } else if (isNull(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        } else if (isNull(ip)) {
            ip = request.getHeader("X-Real-IP");
        } else if (isNull(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        } else if (isNull(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        } else if (isNull(ip)) {
            ip = request.getRemoteAddr();
        } else if (ip.contains(comma)) {
            ip = ip.split(",")[0];
        } else if (localhostIP.equals(ip) || commonIP.equals(ip)) {
            ip = "127.0.0.1";
        }
        Integer ipNum = redisTemplate.opsForValue().get(ip);
//        同一个ip如果注册5次则不再发送短信
        if (ipNum == null) {
            redisTemplate.opsForValue().set(ip, 1);
        } else {
            redisTemplate.opsForValue().set(ip, ++ipNum);
            if (ipNum > 5) {
                return ResponseDTO.wrap(MerChantResponseCodeConstant.IP_NIMIETY);
            }
        }
//        生成六位验证码
        String verificationCode = "";
//        有效时间
        Integer periodOfValidity = 24;
        HttpResult httpResult;
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            verificationCode += random.nextInt(10);
        }
//        redis防止有人恶意注册 注册失败三次则一月内不再发送短信
        Integer integer = redisTemplate.opsForValue().get(number);
        if (integer == null) {
            try {
                httpResult = textMessageVerificationTools.sendMessage(sign, "164549", number, Integer.valueOf(verificationCode) + "##" + periodOfValidity);
            } catch (Exception e) {
                e.printStackTrace();
            }
            redisTemplate.opsForValue().set(number, 1, periodOfValidity, TimeUnit.HOURS);
            redisTemplate.opsForValue().set("YZM" + number, Integer.valueOf(verificationCode), periodOfValidity, TimeUnit.HOURS);
        } else {
            Long time = redisTemplate.getExpire(number);
            redisTemplate.opsForValue().set(number, ++integer);
            Date date = new Date(Instant.now().toEpochMilli() + time * 1000);
            redisTemplate.expireAt(number, date);
            if (integer > 3) {
                return ResponseDTO.wrap(MerChantResponseCodeConstant.FREQUENCY);
            }
            Integer integer1 = redisTemplate.opsForValue().get("YZM" + number);
            try {
                httpResult = textMessageVerificationTools.sendMessage(sign, "164549", number, integer1 + "##" + periodOfValidity);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return ResponseDTO.succMsg("发送成功！");
    }

//    @PostMapping("/login")
//    @ApiOperation("商家登陆")
//    public ResponseDTO login(String username,String password) {
//        UserEntity userEntity = userService.getOne(Wrappers.<UserEntity>lambdaQuery().eq(UserEntity::getUsername, username));
//
//        return ResponseDTO.succMsg("登陆成功！");
//    }

    @PostMapping("/reg")
    @ApiOperation("商家注册")
    public ResponseDTO reg(@RequestBody @Valid UserRegVO userRegVO) {
//        校验邀请码
        ResponseDTO responseDTO = authenticationInvitationCode();
        if(responseDTO.getCode().equals(200)){
            return responseDTO;
        }
        UserEntity userEntity = new UserEntity();
        BeanUtils.copyProperties(userRegVO, userEntity);
        boolean save = userService.save(userEntity);
        if (save) {
            redisTemplate.delete("YZM" + userRegVO.getUsername());
            return ResponseDTO.succMsg("注册成功！");
        }
        return ResponseDTO.wrap(MerChantResponseCodeConstant.REG_ERROR);
    }

    @PostMapping("/modifyPassword")
    @ApiOperation("商家修改密码")
    public ResponseDTO modifyPassword(@RequestBody @Valid UserModifyPasswordVO userModifyPasswordVO) {

        return ResponseDTO.succMsg("修改成功！");
    }

    @PostMapping("/authenticationInvitationCode")
    @ApiOperation("商家验证邀请码")
    public ResponseDTO authenticationInvitationCode() {

        return ResponseDTO.succMsg("邀请码正确！");
    }
}
